<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>setState的两种写法</title>
    <style></style>
  </head>
  <body>
    <div id="test"></div>
    <!-- 引入react核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入react Dom库 用于支持 react操作dom-->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入babel 用于将 jsx 转为 js -->
    <script src="../js/babel.min.js"></script>

    <!-- 使用babel 转译jsx -->
    <script type="text/babel">
      // 1.创建虚拟DOM

      class StateDemo extends React.Component {
        state = { count: 0 };
        add = () => {
          const { count } = this.state;
          // setState的两种写法
          //第一种：状态式 状态更新异步,后面这个回调可选可不选，调用时机是在状态更新完值以后
          //this.setState({ count: count + 1 }, () => {});
          //第二种：函数式
          this.setState((state, props) => {
            return { count: state.count + 1 };
          });
        };
        render() {
          return (
            <div>
              <h1>{this.state.count}</h1>
              <button onClick={this.add}>+1</button>
            </div>
          );
        }
      }
      ReactDOM.render(<StateDemo />, document.getElementById("test"));
    </script>
  </body>
</html>
